package com.myorg.service;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import com.myorg.util.ConstantsToBeExternalized;

public class StartupService {
	private static Runnable SHUTDOWN_RUNNABLE = null;
	private static long LAST_ACCESSED_TIMESTAMP = System.currentTimeMillis();

	public static void touch() {
		LAST_ACCESSED_TIMESTAMP = System.currentTimeMillis();
	}

	private static void shutdownServer() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				int result = 0;
				do {
					String url = ConstantsToBeExternalized.SHUTDOWN_NOTIFICATION_URL;
					System.err.println(">>>>>> Hitting shutdown url: " + url);
					result = sendGet(url);
					try {
						Thread.sleep(10 * 1000L);
					} catch (InterruptedException e) {
						e.printStackTrace();
						throw new RuntimeException(e);
					}
				} while (result != 200);
			}
		}).start();
	}

	private static int sendGet(String url) {
		try {
			URL obj = new URL(url);
			HttpURLConnection con = (HttpURLConnection) obj.openConnection();
			con.setRequestMethod("GET");
			con.setRequestProperty("User-Agent", "Mozilla/5.0");
			return con.getResponseCode();
		} catch (IOException e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static void startup() {
		if (SHUTDOWN_RUNNABLE == null) {
			SHUTDOWN_RUNNABLE = new Runnable() {
				@Override
				public void run() {
					while (true) {
						try {
							Thread.sleep(5 * 1000L);
						} catch (InterruptedException e) {
							e.printStackTrace();
							throw new RuntimeException(e);
						}

						if (System.currentTimeMillis() - LAST_ACCESSED_TIMESTAMP > ConstantsToBeExternalized.MAX_SERVER_IDLE_TIME_BEFORE_SHUTDOWN) {
							new Thread(new Runnable() {
								@Override
								public void run() {
									shutdownServer();
								}
							}).start();
							break;
						}
					}
				}
			};

			new Thread(SHUTDOWN_RUNNABLE).start();
			System.err.println(">>>>>> Start to monitor the idleness of the server.");
		}
	}
}
